package com.zoke.support.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.GridView;

/**
 * 适配在ScrollView中的GrideView
 * 
 * @author JackWu
 * @version
 * @date 2014-10-29
 * @_QQ_ 651319154
 */
public class ScrollGrideView extends GridView {
	private View child;

	public ScrollGrideView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public ScrollGrideView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public ScrollGrideView(Context context) {
		super(context);
	}

	/**
	 * 解决ScrollView与GrideView的嵌套问题,修改前：scrollview占不满全屏是gridview为warpcontent。修改后：
	 * 占不满全屏是gridview填充剩余的部分，超过全屏是gridview显示全部 change_by_dsr
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int thishigh = 0;
		int countchild = getAdapter() == null ? 0 : getAdapter().getCount();
		if (countchild > 0) {
			child = getAdapter().getView(0, null, this);
			if (child == null) {
				super.onMeasure(widthMeasureSpec, heightMeasureSpec);
				return;
			}
			AbsListView.LayoutParams p = (AbsListView.LayoutParams) child.getLayoutParams();
			if (p == null) {
				p = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
						ViewGroup.LayoutParams.WRAP_CONTENT, 0);
				child.setLayoutParams(p);
			}

			int childHeightSpec = getChildMeasureSpec(
					MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 0, p.height);
			int childWidthSpec = getChildMeasureSpec(
					MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 0, p.width);
			child.measure(childWidthSpec, childHeightSpec);

		}
		for (int i = 0; i < countchild; i += 4) {
			thishigh += child.getMeasuredHeight();
		}
		if (thishigh < MeasureSpec.getSize(heightMeasureSpec)) {
			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		} else {
			super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST));
		}
	}

}
